const router = require("express").Router();
const sql = require("../mysql");
const FollowUp = require("../mysql/collection/FollowUp");
const Lead = require("../mysql/collection/Lead");
const Opportunity = require("../mysql/collection/Opportunity");

/**
 * @api {GET} /admin/crm/followups 获取跟进记录列表
 * @apiName GetFollowUps
 * @apiGroup CRM-FollowUp
 *
 * @apiParam {Number} [page=1] 页码
 * @apiParam {Number} [pageSize=10] 每页数量
 * @apiParam {String} [leadId] 线索ID筛选
 * @apiParam {String} [opportunityId] 商机ID筛选
 * @apiParam {String} [type] 跟进类型筛选
 * @apiParam {String} [createdBy] 创建人筛选
 * @apiParam {String} [keyword] 关键词搜索(跟进内容)
 *
 * @apiHeader {String} token 认证令牌
 *
 * @apiSuccess {String} code 状态码
 * @apiSuccess {String} message 描述
 * @apiSuccess {Object} data 数据
 * @apiSuccess {Array} data.list 跟进记录列表
 * @apiSuccess {Number} data.total 总数
 * @apiSuccess {Number} data.page 当前页
 * @apiSuccess {Number} data.pageSize 每页数量
 */
router.get("/followups", async (req, res) => {
  try {
    const { page = 1, pageSize = 10, leadId, opportunityId, type, createdBy, keyword } = req.query;
    const skip = (page - 1) * pageSize;
    
    // 构建查询条件
    let query = {};
    if (leadId) query.leadId = leadId;
    if (opportunityId) query.opportunityId = opportunityId;
    if (type) query.type = type;
    if (createdBy) query.createdBy = createdBy;
    if (keyword) {
      query.content = { $regex: keyword, $options: 'i' };
    }
    
    const total = await FollowUp.countDocuments(query);
    const list = await FollowUp.find(query)
      .populate('leadId', 'name company phone')
      .populate('opportunityId', 'title value stage')
      .populate('createdBy', 'adminname')
      .sort({ createTime: -1 })
      .skip(skip)
      .limit(parseInt(pageSize));
    
    res.send({
      code: "200",
      message: "获取跟进记录列表成功",
      data: {
        list,
        total,
        page: parseInt(page),
        pageSize: parseInt(pageSize)
      }
    });
  } catch (error) {
    res.send({
      code: "500",
      message: "获取跟进记录列表失败",
      error: error.message
    });
  }
});

/**
 * @api {POST} /admin/crm/followups 创建跟进记录
 * @apiName CreateFollowUp
 * @apiGroup CRM-FollowUp
 *
 * @apiParam {String} [leadId] 关联线索ID
 * @apiParam {String} [opportunityId] 关联商机ID
 * @apiParam {String} content 跟进内容
 * @apiParam {String} [type] 跟进类型
 * @apiParam {Date} [nextFollowUp] 下次跟进时间
 *
 * @apiHeader {String} token 认证令牌
 *
 * @apiSuccess {String} code 状态码
 * @apiSuccess {String} message 描述
 * @apiSuccess {Object} data 跟进记录数据
 */
router.post("/followups", async (req, res) => {
  try {
    const followUpData = {
      ...req.body,
      createdBy: req.user._id // 从JWT token中获取ObjectId
    };
    
    // 验证至少有一个关联对象
    if (!followUpData.leadId && !followUpData.opportunityId) {
      return res.send({
        code: "400",
        message: "跟进记录必须关联线索或商机"
      });
    }
    
    const followUp = await FollowUp.create(followUpData);
    const populatedFollowUp = await FollowUp.findById(followUp._id)
      .populate('leadId', 'name company phone')
      .populate('opportunityId', 'title value stage')
      .populate('createdBy', 'adminname');
    
    res.send({
      code: "200",
      message: "创建跟进记录成功",
      data: populatedFollowUp
    });
  } catch (error) {
    res.send({
      code: "500",
      message: "创建跟进记录失败",
      error: error.message
    });
  }
});

/**
 * @api {GET} /admin/crm/followups/:id 获取跟进记录详情
 * @apiName GetFollowUpDetail
 * @apiGroup CRM-FollowUp
 *
 * @apiParam {String} id 跟进记录ID
 *
 * @apiHeader {String} token 认证令牌
 *
 * @apiSuccess {String} code 状态码
 * @apiSuccess {String} message 描述
 * @apiSuccess {Object} data 跟进记录详情
 */
router.get("/followups/:id", async (req, res) => {
  try {
    const followUp = await FollowUp.findById(req.params.id)
      .populate('leadId', 'name company phone')
      .populate('opportunityId', 'title value stage')
      .populate('createdBy', 'adminname');
    
    if (!followUp) {
      return res.send({
        code: "404",
        message: "跟进记录不存在"
      });
    }
    
    res.send({
      code: "200",
      message: "获取跟进记录详情成功",
      data: followUp
    });
  } catch (error) {
    res.send({
      code: "500",
      message: "获取跟进记录详情失败",
      error: error.message
    });
  }
});

/**
 * @api {PUT} /admin/crm/followups/:id 更新跟进记录信息
 * @apiName UpdateFollowUp
 * @apiGroup CRM-FollowUp
 *
 * @apiParam {String} id 跟进记录ID
 * @apiParam {String} [content] 跟进内容
 * @apiParam {String} [type] 跟进类型
 * @apiParam {Date} [nextFollowUp] 下次跟进时间
 *
 * @apiHeader {String} token 认证令牌
 *
 * @apiSuccess {String} code 状态码
 * @apiSuccess {String} message 描述
 * @apiSuccess {Object} data 更新后的跟进记录数据
 */
router.put("/followups/:id", async (req, res) => {
  try {
    const followUp = await FollowUp.findByIdAndUpdate(
      req.params.id,
      req.body,
      { new: true }
    ).populate('leadId', 'name company phone')
     .populate('opportunityId', 'title value stage')
     .populate('createdBy', 'adminname');
    
    if (!followUp) {
      return res.send({
        code: "404",
        message: "跟进记录不存在"
      });
    }
    
    res.send({
      code: "200",
      message: "更新跟进记录信息成功",
      data: followUp
    });
  } catch (error) {
    res.send({
      code: "500",
      message: "更新跟进记录信息失败",
      error: error.message
    });
  }
});

/**
 * @api {GET} /admin/crm/followups/lead/:leadId 获取线索的跟进记录
 * @apiName GetLeadFollowUps
 * @apiGroup CRM-FollowUp
 *
 * @apiParam {String} leadId 线索ID
 * @apiParam {Number} [page=1] 页码
 * @apiParam {Number} [pageSize=10] 每页数量
 *
 * @apiHeader {String} token 认证令牌
 *
 * @apiSuccess {String} code 状态码
 * @apiSuccess {String} message 描述
 * @apiSuccess {Object} data 跟进记录列表
 */
router.get("/followups/lead/:leadId", async (req, res) => {
  try {
    const { page = 1, pageSize = 10 } = req.query;
    const skip = (page - 1) * pageSize;
    
    const total = await FollowUp.countDocuments({ leadId: req.params.leadId });
    const list = await FollowUp.find({ leadId: req.params.leadId })
      .populate('createdBy', 'adminname')
      .sort({ createTime: -1 })
      .skip(skip)
      .limit(parseInt(pageSize));
    
    res.send({
      code: "200",
      message: "获取线索跟进记录成功",
      data: {
        list,
        total,
        page: parseInt(page),
        pageSize: parseInt(pageSize)
      }
    });
  } catch (error) {
    res.send({
      code: "500",
      message: "获取线索跟进记录失败",
      error: error.message
    });
  }
});

/**
 * @api {GET} /admin/crm/followups/opportunity/:opportunityId 获取商机的跟进记录
 * @apiName GetOpportunityFollowUps
 * @apiGroup CRM-FollowUp
 *
 * @apiParam {String} opportunityId 商机ID
 * @apiParam {Number} [page=1] 页码
 * @apiParam {Number} [pageSize=10] 每页数量
 *
 * @apiHeader {String} token 认证令牌
 *
 * @apiSuccess {String} code 状态码
 * @apiSuccess {String} message 描述
 * @apiSuccess {Object} data 跟进记录列表
 */
router.get("/followups/opportunity/:opportunityId", async (req, res) => {
  try {
    const { page = 1, pageSize = 10 } = req.query;
    const skip = (page - 1) * pageSize;
    
    const total = await FollowUp.countDocuments({ opportunityId: req.params.opportunityId });
    const list = await FollowUp.find({ opportunityId: req.params.opportunityId })
      .populate('createdBy', 'adminname')
      .sort({ createTime: -1 })
      .skip(skip)
      .limit(parseInt(pageSize));
    
    res.send({
      code: "200",
      message: "获取商机跟进记录成功",
      data: {
        list,
        total,
        page: parseInt(page),
        pageSize: parseInt(pageSize)
      }
    });
  } catch (error) {
    res.send({
      code: "500",
      message: "获取商机跟进记录失败",
      error: error.message
    });
  }
});

/**
 * @api {DELETE} /admin/crm/followups/:id 删除跟进记录
 * @apiName DeleteFollowUp
 * @apiGroup CRM-FollowUp
 *
 * @apiParam {String} id 跟进记录ID
 *
 * @apiHeader {String} token 认证令牌
 *
 * @apiSuccess {String} code 状态码
 * @apiSuccess {String} message 描述
 */
router.delete("/followups/:id", async (req, res) => {
  try {
    const followUp = await FollowUp.findByIdAndDelete(req.params.id);
    
    if (!followUp) {
      return res.send({
        code: "404",
        message: "跟进记录不存在"
      });
    }
    
    res.send({
      code: "200",
      message: "删除跟进记录成功"
    });
  } catch (error) {
    res.send({
      code: "500",
      message: "删除跟进记录失败",
      error: error.message
    });
  }
});

module.exports = router;